package cc.eddic.pratice.programmingparadigms.emp02list.impl;

import cc.eddic.pratice.programmingparadigms.Result;
import cc.eddic.pratice.programmingparadigms.ResultComparator;
import cc.eddic.pratice.programmingparadigms.emp02list.ResultList;

public class ResultListZyzImpl implements ResultList {
    private Result[] results;
    private int index = 0;
    private static final int DEFAULT_INITIAL_CAPACITY = 10;

    public ResultListZyzImpl(Result[] results) {
        this.results = new Result[results.length];
        for (int i = 0; i < results.length; i++) {
            this.results[i] = results[i];
        }
    }

    public ResultListZyzImpl() {
        this.results = new Result[DEFAULT_INITIAL_CAPACITY];
    }

    public ResultListZyzImpl(int initialCapacity) {
        this.results = new Result[initialCapacity];
    }

    @Override
    public int size() {
        return this.index;
    }

    @Override
    public Result get(int index) {
        if (index >= size()) {
            String msg = String.format("Index: %d, Size: %d",  index, size());
            throw new IndexOutOfBoundsException(msg);
        }
        return this.results[index];
    }

    @Override
    public void add(Result result) {
        if (index > capacity()) {
            scaleOutCapacity();
        }
        this.results[this.index] = result;
        this.index++;
    }

    @Override
    public int capacity() {
        return this.results.length;
    }


    private void scaleOutCapacity() {
        int currentCapacity = capacity();
        int scaledCapacity = currentCapacity * 2;
        Result[] newResults = new Result[scaledCapacity];
        for (int i = 0; i < currentCapacity; i++) {
            newResults[i] = results[i];
        }
        this.results = newResults;
    }

    @Override
    public Result findByGender(String gender) {
        for(int i=0;i<size();i++){
            if(get(i).equals(gender)){
                return get(i);
            }
        }
        return null;
    }

    @Override
    public Result findByDepartment(String department) {
        for(int i=0;i<size();i++){
            if(get(i).equals(department)){
                return get(i);
            }
        }
        return null;
    }

    @Override
    public Result findByJobTitle(String jobTitle) {
        for(int i=0;i<size();i++){
            if(get(i).equals(jobTitle)){
                return get(i);
            }
        }
        return null;
    }

    public void sort(ResultComparator comparator) {
        for (int i = 0; i < size(); i++) {
            for (int j = 0; j < size() - i - 1; j++) {
                if (comparator.compare(results[j], results[j + 1]) > 0) {
                    Result temp = results[j];
                    results[j] = results[j + 1];
                    results[j + 1] = temp;
                }
            }
        }
    }

}
